<template>
  <div class="container" ref="mainCon">
    <salaryTopTitle
      :title="isRejecded == 1 ? batchNoInfo : ''"
      :rejectReason="isRejecded == 1 ? rejectReason : ''"
      :isRejecded="isRejecded"
      @gobackTriser="goBack"
    ></salaryTopTitle>
    <div :class="isRejecded == 1 ? 'mainCon mainConReject' : 'mainCon '">
      <createSalaryStep
        :activeIndex="activeIndex"
        style="padding-bottom: 24px"
      ></createSalaryStep>
      <div class="spacing"></div>
      <div style="width: 100%; height: 30px"></div>
      <div v-if="!finished">
        <el-row
          class="toolbar searchInputWidth"
          style="padding: 24px 24px 0 !important"
        >
          <el-form :inline="true" :model="filterField" ref="searchConditions">
            <el-col :lg="8" :xl="6">
              <el-form-item label="参建单位" class="row-padding-bottom">
                <el-select
                  v-model="filterField.uscc"
                  :disabled="isFenbaoManager"
                  clearable
                  filterable
                  placeholder="请选择"
                  @change="changeCompany"
                >
                  <el-option
                    v-for="(item, index) of companyList"
                    :key="index"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="班组" class="row-padding-bottom">
                <el-select
                  v-model="filterField.groupId"
                  clearable
                  filterable
                  placeholder="请先选择参建单位"
                >
                  <el-option
                    v-for="(item, index) of groupIdOptions"
                    :key="index"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <template v-if="advanced">
              <el-col :lg="8" :xl="6">
                <el-form-item label="姓名" class="row-padding-bottom">
                  <el-input
                    placeholder="请输入内容"
                    clearable
                    class="input"
                    v-model="filterField.name"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :lg="8" :xl="6">
                <el-form-item label="手机号" class="row-padding-bottom">
                  <el-select
                    v-model="filterField.hasTel"
                    clearable
                    filterable
                    placeholder="请先选择手机号"
                  >
                    <el-option
                      v-for="(item, index) of selectOptions"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :lg="8" :xl="6">
                <el-form-item label="银行卡号" class="row-padding-bottom">
                  <el-select
                    v-model="filterField.hasAccount"
                    clearable
                    filterable
                    placeholder="请先选择银行卡号"
                  >
                    <el-option
                      v-for="(item, index) of selectOptions"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </template>
            <el-col :lg="8" :xl="8">
              <el-form-item label="">
                <a
                  @click="toggleAdvanced"
                  style="margin-left: 40px; color: #409eff; cursor: pointer"
                  class="btnColor"
                >
                  {{ advanced ? '收起' : '展开' }}
                  <i
                    :class="
                      advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
                    "
                  ></i>
                </a>
                <el-button
                  type="primary"
                  icon="icon iconfont iconchazhao1"
                  @click="searchBrand"
                  class="searchBtn"
                >
                  <span>搜索</span>
                </el-button>
                <el-button
                  class="commonBut saveBtn funComBut"
                  icon="icon iconfont icondaochu"
                  @click="exportSalaryPayBatchList"
                >
                  <span class="opetareText">导出</span>
                </el-button>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
        <div class="spacing"></div>
        <div
          ref="tableBox"
          :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
        >
          <div style="margin-bottom: 24px">
            <el-button
              icon="icon iconfont icontianjia"
              @click="toAddPeople"
              class="commonBut saveBtn funComBut"
              ><span class="opetareText">添加人员</span>
            </el-button>
          </div>
          <el-table
            :data="tableList"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
            highlight-current-row
            stripe
            style="border: 1px solid #dfe6ec"
            @row-click="clickRow"
            type="index"
            :row-class-name="tableRowClassName"
            @sort-change="sortChange"
            v-loading="loading"
            :max-height="tableHeight"
          >
            <el-table-column
              type="index"
              width="80px"
              label="序号"
              align="center"
            ></el-table-column>
            <!-- <el-table-column prop="companyName" label="参建单位"  align="center" :formatter=formatTd></el-table-column>  -->
            <el-table-column prop="companyName" label="参建单位" width="230">
              <template slot-scope="scope">
                <copyText
                  :tableIndex="scope.$index"
                  :copyTextName="scope.row.companyName"
                  :columnName="'companyName'"
                ></copyText>
              </template>
            </el-table-column>
            <el-table-column
              prop="groupName"
              label="班组"
              width="200"
              align="center"
              :formatter="formatTd"
            ></el-table-column>
            <el-table-column
              prop="name"
              label="姓名"
              align="center"
              width="140"
              :formatter="formatTd"
            ></el-table-column>
            <el-table-column
              prop="idcard"
              label="身份证"
              align="center"
              width="175px"
              :formatter="formatTd"
            ></el-table-column>
            <el-table-column
              prop="attTotal"
              label="考勤天数"
              align="center"
              :formatter="formatTd"
              width="120"
            ></el-table-column>
            <el-table-column
              prop="tel"
              label="手机号"
              align="center"
              width="150"
            >
              <template slot-scope="{ row, $index }">
                <div
                  @click.stop="
                    {
                      {
                        changeNum($index, 'editBankInput')
                      }
                    }
                  "
                >
                  <el-input
                    v-if="editable[$index] && !isDisable"
                    v-model="row.tel"
                    size="mini"
                    class="editBankInput"
                  ></el-input>
                  <span v-else>{{ row.tel || '--' }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="account"
              label="银行卡号"
              align="center"
              width="185px"
            >
              <template slot-scope="{ row, $index }">
                <div
                  @click.stop="
                    {
                      {
                        changeNum($index, 'editPersonaccountInput')
                      }
                    }
                  "
                >
                  <el-input
                    v-if="editable[$index] && !isDisable"
                    v-model="row.account"
                    size="mini"
                    class="editPersonaccountInput"
                    maxlength="64"
                  ></el-input>
                  <span v-else>{{ row.account || '--' }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="shouldPay"
              label="应发工资"
              align="center"
              sortable="custom"
              width="120"
            >
              <template slot-scope="{ row, $index }">
                <div
                  @click.stop="
                    {
                      {
                        changeNum($index, 'editSalaryInput')
                      }
                    }
                  "
                >
                  <el-input
                    v-if="editable[$index] && !isDisable"
                    v-model="row.shouldPay"
                    size="mini"
                    class="editSalaryInput"
                  ></el-input>
                  <span v-else>{{ row.shouldPay }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" align="center">
              <template slot-scope="{ row, $index }">
                <div
                  @click.stop="
                    {
                      {
                        changeNum($index, 'editRemarkInput')
                      }
                    }
                  "
                  v-if="!checkEmployee(row)"
                >
                  <el-input
                    v-if="editable[$index] && !isDisable"
                    v-model="row.remark"
                    size="mini"
                    class="editRemarkInput"
                  ></el-input>
                  <span
                    v-else
                    :class="
                      row.remark && row.remark.indexOf('未录入系统人员') !== -1
                        ? 'redColor'
                        : ''
                    "
                    >{{ row.remark || '--' }}</span
                  >
                </div>
                <div v-else>
                  <span class="redColor">{{ row.remark || '--' }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              min-width="80"
              align="left"
              fixed="right"
            >
              <template slot-scope="{ row, $index }">
                <el-link
                  type="primary"
                  @click.stop="handleSave(row, $index)"
                  v-if="editable[$index] && !isDisable"
                  >保存</el-link
                >
                <el-link
                  type="primary"
                  @click.stop="cancelSave(row, $index, 'true')"
                  v-if="editable[$index] && !isDisable"
                  >取消</el-link
                >
                <!-- <span class="delIcon" @click.stop="handleDelete(row , $index)" v-if="!editable[$index]">删除</span> -->
                <el-link
                  type="primary"
                  @click.stop="handleDelete(row, $index)"
                  v-if="!editable[$index]"
                  >删除</el-link
                >
                <!-- <i
                    class="icon iconfont iconshanchu tabIcon delIcon"
                    @click.stop="handleDelete(row , $index)"
                    v-if="!editable[$index]"
                    ></i> -->
              </template>
            </el-table-column>
            <!-- 表格数据为空时，页面显示 -->
            <div slot="empty" v-show="isShow">
              <emptyTable emptyText="暂无相关信息"></emptyTable>
            </div>
          </el-table>
          <el-col :span="24" class="toolbar" style="text-align: right">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              ref="pagination"
            ></el-pagination>
          </el-col>
        </div>
        <el-col class="btnContainer">
          <el-button
            class="commonBut saveBtn"
            @click="isPay"
            :loading="isPyLoading"
            :disabled="isDisable"
            >{{ review ? '通过' : '下一步' }}</el-button
          >
          <el-button
            class="commonBut rejectBtn"
            v-if="review"
            @click="refused"
            :loading="isPyLoading"
            >驳回</el-button
          >
          <el-button
            class="commonBut"
            @click="toSaveSalary"
            :loading="isSaveLoading"
            :disabled="isDisable"
            >保存</el-button
          >
        </el-col>
      </div>
      <subcontract-salary-result
        :year="year"
        :month="month"
        :batchNo="batchNo"
        v-if="finished"
      />
    </div>

    <!--新增人员-->
    <dialogAddSalaryEmplyee
      :formVisible="formVisible"
      :projectId="projectId"
      :year="year"
      :month="month"
      :salaryId="salaryId"
      :projectName="projectName"
      @callback="callbackAddEmplyee"
    />
    <!-- 驳回弹窗 -->
    <dialogRefused
      :showTaskProp="showTask"
      @callback="handleCloseArea"
      :salaryId="salaryId"
      @getStatusQuery="getStatusQuery(arguments)"
    />
  </div>
</template>

<script>
import createSalaryStep from '@/components/publicCom/createSalaryStepJz'
import salaryTopTitle from '@/components/publicCom/salaryTopTitle'
import dialogRefused from '@/components/publicCom/dialogRefused.vue'
import { mapState, mapActions } from 'vuex'
import dialogAddSalaryEmplyee from './dialogAddSalaryEmplyee.vue'
import SubcontractSalaryResult from './subcontractSalaryResult.vue'
import common from '../../kits/common'
export default {
  name: 'editConstructSalary',
  components: {
    createSalaryStep,
    salaryTopTitle,
    dialogRefused,
    dialogAddSalaryEmplyee,
    SubcontractSalaryResult,
  },
  data() {
    return {
      lastItem: '编辑工资表',
      advanced: false,
      activeIndex: 1,
      // requestUrl:"api-su/salarydetail/base/vo",
      isPackParams: true,
      //下拉框数据
      companyList: [],
      //表格数据
      tableList: [],
      //分页
      currentPage: 1,
      total: 0,
      pageSize: 10,
      //搜索条件
      filterField: {
        groupId: '',
        name: '',
        uscc: '',
        hasBank: '',
        hasPhone: '',
        // department: ""
      },
      orgId: '',
      editable: [], //是否可保存
      saveItem: '', //保存项
      formVisible: false, //添加人员弹窗
      isDisable: false,
      isVerify: true,
      state: '',
      timeout: null,
      // 页面传值
      salaryId: '',
      accountList: [
        {
          value: 'not null',
          label: '有银行卡号',
        },
        {
          value: 'null',
          label: '无银行卡号',
        },
      ],
      selectOptions: [
        {
          value: '1',
          label: '已填写',
        },
        {
          value: '0',
          label: '未填写',
        },
      ],
      // 保存loading
      isSaveLoading: false,
      // 立即支付loading
      isPyLoading: false,
      // 记录编辑的那一行的原始数据
      firstObjP: {
        shouldPay: '',
        // calcPay: "",
        account: '',
        tel: '',
        remark: '',
      },
      isShow: false,
      loading: true,
      // ie9定时器
      timer: null,
      isIE9: false,
      year: '2019',
      month: '06',
      batchNo: '',
      projectId: '',
      shouldPayOfAll: '',
      projectName: '',
      type: '',
      showTask: false,
      caseInfo: {},
      isFenbaoManager: false, //是否分包单位
      review: 0, //是否是驳回操作
      finished: false,
      isRejecded: 0,
      batchNoInfo: '',
      rejectReason: '',
    }
  },
  created() {
    console.log(this.$store.state)
    //判断是否为分包单位
    if (this.$store.state.accountType == 'FENBAO_MANAGER') {
      console.log(11)
      this.isFenbaoManager = true
      this.filterField.uscc = this.$store.state.uscc
      this.changeCompany()
    }
    this.$store.commit('SET_INFO', ['groupIdOptions', []])
    this.salaryId = this.$route.query.salaryId
    this.year = this.$route.query.year
    this.month = this.$route.query.month
    this.filterField.salaryId = this.salaryId
    this.projectId = this.$route.query.projectId
    this.projectName = this.$route.query.projectName
    this.type = this.$route.query.type
    this.review = this.$route.query.review
    this.batchNo = this.$route.query.batchNo
    this.batchNoInfo = this.$route.query.batchNoInfo
    this.rejectReason = this.$route.query.rejectReason
    this.isRejecded = this.$route.query.isRejecded //判断是否是被驳回过的工资表
    // this.$nextTick(function() {
    //   this.$refs.pagination.getTableListData();
    // });
    this.getCompanyList()
    this.getTableList(this.currentPage, this.pageSize)

    this.isIE()
  },
  computed: {
    ...mapState(['groupIdOptions']),
  },
  methods: {
    exportSalaryPayBatchList() {
      if (this.tableList.length > 0) {
        var fieldArr = [
          'companyName',
          'groupName',
          'name',
          'idcard',
          'attTotal',
          'tel',
          'account',
          'shouldPay',
          'remark',
        ]
        // for(var i =0; i < this.tableCol.length;i++) {
        //     if(this.tableCol[i].isShow == true) {
        //     fieldArr.push(this.tableCol[i].prop)
        //     }
        // }
        fieldArr = fieldArr.join(',')
        window.location.href =
          common.commonApi +
          'api-su/cs/salarydetail/expand/newSalaryDetailReport?salaryId=' +
          this.salaryId +
          '&year=' +
          this.year +
          '&uscc=' +
          this.filterField.uscc +
          '&groupId=' +
          this.filterField.groupId +
          '&name=' +
          this.filterField.name +
          '&field=' +
          fieldArr +
          '&access_token=' +
          localStorage.getItem('access_token')
      } else {
        this.$message({
          type: 'warning',
          message: '无数据导出',
        })
      }
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    ...mapActions(['getGroupList']),
    getTableList(currentPage, pageSize) {
      var data = {
        pageNo: currentPage,
        pageSize: pageSize,
        uscc: '', //参建单位uscc
        groupId: '', //班组id
        name: '', //姓名
      }
      this.filterField.salaryId = this.salaryId
      this.filterField.year = this.year
      this.filterField.month = this.month
      data = Object.assign(data, this.filterField)
      //   data.params = JSON.stringify(this.filterField);
      this.axios({
        method: 'post',
        url: 'api-su/cs/salarydetail/expand/list',
        data: data,
      })
        .then(
          (response) => {
            this.tableList = response.data.result.results
            this.loading = false
            if (this.tableList.length < 1) {
              this.isShow = true
            }
            this.total = response.data.result.total
            this.editable = new Array(this.tableList.length)
            // this.saveItem = [];
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    //每页显示多少条
    handleSizeChange(val) {
      this.isVerify = true
      for (var i = 0; i < this.editable.length; i++) {
        if (this.editable[i]) {
          this.$confirm('当前页面还有数据未保存, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              // 选中条数变为第一页
              this.currentPage = 1
              this.pageSize = val
              this.$refs.pagination.internalCurrentPage = this.currentPage
              this.getTableList(this.currentPage, val)
            })
            .catch(() => {})
          return
        } else {
        }
      }
      this.currentPage = 1
      this.pageSize = val
      this.$refs.pagination.internalCurrentPage = this.currentPage
      this.getTableList(this.currentPage, val)
    },
    //显示第几页
    handleCurrentChange(val) {
      this.isVerify = true
      for (var i = 0; i < this.editable.length; i++) {
        if (this.editable[i]) {
          this.$confirm('当前页面还有数据未保存, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              // 获取数据
              this.getTableList(val, this.pageSize)
            })
            .catch(() => {})
          return
        } else {
        }
      }
      // 获取数据
      this.getTableList(val, this.pageSize)
    },
    handleChange(item) {
      var orgId = this.orgId[this.orgId.length - 1]

      this.filterField.organId = orgId
    },
    //表格过滤
    sortChange(column, prop, order) {
      // column：当前列
      // prop：当前列需要排序的数据
      // order：排序的规则（升序、降序和默认[默认就是没排序]）
      this.filterField.order = column.prop
      this.filterField.sort = column.order
      this.getTableList(this.currentPage, this.pageSize)
    },
    tableRowClassName({ row, rowIndex }) {
      //把每一行的索引放进row
      row.index = rowIndex
    },
    clickRow(row, column, event) {
      var index = row.index
      //验证点击的时候是否需要保存上一行数据
      if (this.editable[index]) {
      } else {
        if (this.saveItem) {
          if (
            this.firstObjP.account == this.saveItem.account &&
            this.firstObjP.remark == this.saveItem.remark &&
            this.firstObjP.shouldPay == this.saveItem.shouldPay &&
            // this.firstObjP.calcPay == this.saveItem.calcPay &&
            this.firstObjP.tel == this.saveItem.tel
          ) {
            this.setEdit(index, '', 'row')
            return
          }
          this.verifyNum(this.saveItem, index, '', 'row')
          if (!this.isVerify) {
            return
          }
        } else {
          // //设置是否可以编辑
          this.setEdit(index, '', 'row')
        }
      }
    },
    changeNum(index, className) {
      //验证点击的时候是否需要保存上一行数据
      if (this.editable[index]) {
      } else {
        if (this.saveItem) {
          if (
            this.firstObjP.account == this.saveItem.account &&
            this.firstObjP.remark == this.saveItem.remark &&
            this.firstObjP.shouldPay == this.saveItem.shouldPay &&
            // this.firstObjP.calcPay == this.saveItem.calcPay &&
            this.firstObjP.tel == this.saveItem.tel
          ) {
            this.setEdit(index, className, 'input')
            return
          }
          this.verifyNum(this.saveItem, index, className, 'input')
          if (!this.isVerify) {
            return
          } else {
          }
        } else {
          this.setEdit(index, className, 'input')
        }
      }
    },
    setEdit(index, className, type) {
      //设置是否可以编辑
      this.editable = new Array(this.tableList.length)
      this.editable[index] = true
      this.saveItem = this.tableList[index]
      this.firstObjP = {
        shouldPay: this.saveItem.shouldPay,
        account: this.saveItem.account,
        // calcPay: this.saveItem.calcPay,
        tel: this.saveItem.tel,
        remark: this.saveItem.remark,
      }

      this.$set(this.editable, index, true)
      // 当应发工资为0，手动清除输入框中的数据
      if (this.saveItem.shouldPay == 0) {
        this.tableList[index].shouldPay = ''
      }

      if (type == 'input') {
        //focus
        this.$nextTick(function () {
          var editInputList = document.getElementsByClassName(className)
          editInputList[0].children[0].focus()
        })
      }
    },
    // 取消编辑
    cancelSave(row, index, isCancel) {
      // this.tableList[index] = this.demo;
      if (isCancel == 'true') {
        this.tableList[index].shouldPay = this.firstObjP.shouldPay
        // this.tableList[index].calcPay = this.firstObjP.calcPay;
        this.tableList[index].account = this.firstObjP.account
        this.tableList[index].tel = this.firstObjP.tel
        // this.tableList[index].shouldPayOfAll = this.firstObjP.shouldPayOfAll;
        this.tableList[index].remark = this.firstObjP.remark
      }

      this.editable = new Array(this.tableList.length)
      this.saveItem = ''
      // 验证条件置为原始值
      this.isVerify = true
    },
    // 搜索
    searchBrand() {
      // this.$refs.pagination.getTableListData();
      this.getTableList(this.currentPage, this.pageSize)
    },
    //验证编辑内容格式
    verifyNum(row, index, className, type) {
      var telReg = /^1[3456789]\d{9}$/
      // var accountReg = /^\d{15,19}$/;
      var accountReg = /^[^\u4e00-\u9fa5]{0,}$/
      var moneyReg = /^\d{1,7}(\.\d{0,2})?$/
      // var remarkReg = /^([\u4E00-\u9FA5]{1,10} )||([A-Za-z0-9 ]{1,20})$/;
      this.isVerify = true
      var text = ''

      if (!telReg.test(row.tel) && row.tel) {
        text += '手机号必须填写11位数字;'
        this.isVerify = false
      }

      if (row.account) {
        var account = row.account.replace(/\s/g, '')
      } else {
        var account = ''
      }

      // if (!accountReg.test(account) && account) {
      //   text += "请输入15-19 位纯数字的银行卡号;";
      //   this.isVerify = false;
      // }

      if (row.shouldPay) {
        if (!moneyReg.test(row.shouldPay)) {
          text += '已超过金额最大值，请重新输入;'
          if (!accountReg.test(account)) {
            text += '请输入正确格式的账号;'
          }
          this.isVerify = false
        } else {
          if (!accountReg.test(account)) {
            text += '请输入正确格式的账号;'
            this.isVerify = false
          }
        }
      } else {
        if (!accountReg.test(account) && account) {
          text += '请输入正确格式的账号;'
          this.isVerify = false
        }
      }

      if (row.remark && row.remark.length > 200) {
        text += '最多输入200字的备注;'
        this.isVerify = false
      }

      if (!this.isVerify) {
        this.$message({
          message: text,
          type: 'warning',
        })
      } else {
        this.savaSalary(row, index, className, type)
      }
    },
    // 保存
    savaSalary(row, index, className, type) {
      var data = {
        salaryId: this.salaryId, //工资表id
        year: this.year, //年
        id: row.id, //工资详情表id
        shouldPay: row.shouldPay || '', //应发工资
        // calcPay: row.calcPay, //结算工资
        account: row.account ? row.account.replace(/\s/g, '') : '', //银行卡号
        tel: row.tel || '', //手机号
        remark: row.remark || '', //备注
        shouldPayOfAll: row.shouldPayOfAll, //应付总金额
        shouldTotalOfAll: row.shouldTotalOfAll,
      }

      var loading = this.$loading({
        lock: true,
        text: '保存中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
      })
      var arr = []
      arr[0] = data
      var querry = {}
      querry.detailJson = JSON.stringify(arr)
      this.axios({
        method: 'post',
        url: 'api-su/cs/salarydetail/expand/update',
        data: querry,
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              loading.close()
              this.$message({
                message: '保存成功',
                type: 'success',
              })

              //需刷新
              this.$nextTick(function () {
                this.getTableList(this.currentPage, this.pageSize)
                this.cancelSave(row, index)
              })

              // 需要判断
              if (type) {
                var that = this
                setTimeout(function () {
                  that.setEdit(index, className, type)
                }, 500)
              }
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'warning',
              })
              loading.close()
              // this.isVerify = false;
            }
          },
          (response) => {
            this.$message({
              message: '数据请求失败',
              type: 'warning',
            })
            loading.close()
          }
        )
        .catch((error) => {
          loading.close()
        })
    },
    //删除
    handleDelete(row, index) {
      const h = this.$createElement
      this.shouldPayOfAll = row.shouldPayOfAll
      this.$msgbox({
        title: '删除人员',
        type: 'warning',
        message: h('p', null, [
          h('p', null, '是否确认工资表中删除 '),
          h('p', null, row.name + '-' + row.idcard + '?'),
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then((action) => {
          this.delPeople(row, index)
        })
        .catch(() => {
          //     // this.$message.error("删除失败");
        })
    },
    delPeople(row, index) {
      var loading = this.$loading({
        lock: true,
        text: '处理中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
      })
      var data = {
        shouldPayOfAll: this.shouldPayOfAll, //应付总金额
        year: this.year,
        id: row.id, //工资详情id
        shouldTotalOfAll: row.shouldTotalOfAll,
      }
      this.axios({
        method: 'post',
        url: 'api-su/cs/salarydetail/expand/delete',
        data: data,
      })
        .then(
          (response) => {
            loading.close()
            if (!response.data.hasError) {
              this.$message({
                message: '删除成功',
                type: 'success',
              })
              this.$nextTick(function () {
                // this.$refs.pagination.getTableListData();
                this.getTableList(this.currentPage, this.pageSize)
              })
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'warning',
              })
            }
          },
          (response) => {
            loading.close()
            this.$message({
              message: '数据请求失败',
              type: 'warning',
            })
          }
        )
        .catch((error) => {
          loading.close()
        })
    },
    //表格中的保存
    handleSave(row, index) {
      this.shouldPayOfAll = row.shouldPayOfAll
      this.verifyNum(row, index)
    },
    toAddPeople() {
      this.formVisible = true
    },
    isPay() {
      this.axios
        .post('api-su/cs/salary/expand/checkTelForSalaryDetail', {
          salaryId: this.salaryId,
        })
        .then((res) => {
          console.log(res)
          if (!res.data.hasError) {
            this.isPyLoading = true
            this.axios({
              method: 'post',
              url: 'api-su/cs/salary/expand/rs',
              data: {
                salaryId: this.salaryId,
                year: this.year,
              },
            })
              .then(
                (response) => {
                  this.isPyLoading = false
                  if (!response.data.hasError) {
                    this.batchNo = response.data.result.batchNo
                    this.canpPapOff(response.data.result)
                  } else {
                    this.$message({
                      message: response.data.errorMsg,
                      type: 'warning',
                    })
                  }
                },
                (response) => {
                  this.isPyLoading = false
                  this.$message({
                    message: '数据请求失败',
                    type: 'warning',
                  })
                }
              )
              .catch((error) => {
                this.isPyLoading = false
              })
          } else {
            this.$message({
              message: res.data.errorMsg,
              type: 'warning',
            })
          }
        })
    },

    toPaySalary(data) {
      let falg = 0
      let arr = this.tableList
      if (arr.length) {
        arr.forEach((item) => {
          if (item.remark) {
            if (item.remark.indexOf('未录入系统人员')) {
              falg += 1
            }
          }
        })
      }
      this.axios({
        method: 'post',
        url: 'api-su/cs/salary/expand/ues',
        data: {
          id: this.salaryId,
          year: this.year,
          shouldPay: data.shouldPay,
          calcPay: data.calcPay,
          shouldPayTotal: data.shouldPayTotal,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              // 如果是分包单位，上报工资表以后就结束了，等待项目账号审核
              if (this.$store.state.accountType == 'FENBAO_MANAGER') {
                //    this.fenbaoDFSuccess()

                //劳务公司工资代发业务到上报即结束,返回工资表列表页面
                this.finished = true
              } else {
                this.$router.push({
                  path: '/home/constructSalary/constructPaySalaryWay',
                  name: 'constructPaySalaryWay',
                  query: {
                    salaryId: this.salaryId,
                    year: this.year,
                    month: this.month,
                    projectId: this.projectId,
                    projectName: this.projectName,
                    type: this.type,
                    showNotice: falg,
                    signboard: 'auditSG',
                    review: this.review,
                  },
                })
                this.$store.commit('CHANGE_SLIDER_NAME', {
                  oldUrl: '/home/salaryDf/companySalaryBatchList',
                  newUrl: this.$router.currentRoute.fullPath,
                })
              }
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'warning',
              })
            }
          },
          (response) => {
            this.$message({
              message: '数据请求失败',
              type: 'warning',
            })
          }
        )
        .catch((error) => {})
      // this.$router.push("/home/salary/paySalary");
    },
    toSaveSalary() {
      this.verifySaveItem(this.saveItem)
    },
    //验证编辑内容格式
    verifySaveItem(row) {
      var telReg = /^1[3456789]\d{9}$/
      var accountReg = /^[^\u4e00-\u9fa5]{0,}$/
      var moneyReg = /^\d{1,7}(\.\d{0,2})?$/
      // var remarkReg = /^([\u4E00-\u9FA5]{1,10} )||([A-Za-z0-9 ]{1,20})$/;
      var isVerify = true
      var text = ''

      if (!telReg.test(row.tel) && row.tel) {
        text += '请输入正确的手机号;'
        isVerify = false
      }

      if (row.account) {
        var account = row.account.replace(/\s/g, '')
      } else {
        var account = ''
      }

      if (row.shouldPay) {
        if (!moneyReg.test(row.shouldPay)) {
          text += '已超过金额最大值，请重新输入;'
          if (!accountReg.test(account)) {
            text += '请输入正确格式的账号;'
          }
          isVerify = false
        } else {
          if (!accountReg.test(account)) {
            text += '请输入正确格式的账号;'
            isVerify = false
          }
        }
      } else {
        if (!accountReg.test(account) && account) {
          text += '请输入正确格式的账号;'
          isVerify = false
        }
      }

      if (row.remark && row.remark.length > 200) {
        text += '最多输入200字的备注;'
        isVerify = false
      }

      if (row) {
        if (!isVerify) {
          this.$message({
            message: text,
            type: 'warning',
          })
        } else {
          this.saveSalary()
        }
      } else {
        this.saveSalary()
      }
    },
    //保存
    saveSalary() {
      var list = []
      var arr = []
      for (var i = 0; i < this.tableList.length; i++) {
        var item = this.tableList[i]
        list.push({
          id: item.id,
          salaryId: item.salaryId,
          shouldPay: item.shouldPay || '',
          remark: item.remark || '',
          account: item.account ? item.account.replace(/\s/g, '') : '',
          tel: item.tel || '',
          calcPay: item.calcPay || '',
          year: this.year,
          shouldPayOfAll: item.shouldPayOfAll,
          shouldTotalOfAll: item.shouldTotalOfAll,
        })
        arr[i] = list
      }

      var querry = {}
      querry.detailJson = JSON.stringify(list)

      this.isSaveLoading = true
      this.axios({
        method: 'post',
        url: 'api-su/cs/salarydetail/expand/update',
        data: querry,
      })
        .then(
          (response) => {
            this.isSaveLoading = false
            if (!response.data.hasError) {
              this.$message({
                message: '保存成功',
                type: 'success',
              })

              this.$nextTick(function () {
                // this.$refs.pagination.getTableListData();
                this.getTableList(this.currentPage, this.pageSize)
              })
              this.editable = new Array(this.tableList.length)
              this.saveItem = ''
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'warning',
              })
            }
          },
          (response) => {
            this.isSaveLoading = false
            this.$message({
              message: '数据请求失败',
              type: 'warning',
            })
          }
        )
        .catch((error) => {
          this.isSaveLoading = false
        })
    },
    saveSalarySuccess() {
      this.$confirm(
        '已为您成功保存编辑的工资表, 您可以等以后有空再编辑或继续编辑?',
        '保存成功',
        {
          confirmButtonText: '继续编辑',
          cancelButtonText: '返回列表',
          type: 'success',
        }
      )
        .then(() => {
          // this.$message({
          //   type: 'success',
          //   message: '删除成功!'
          // });
        })
        .catch(() => {
          this.goBack()
        })
    },
    noSalaryAccount() {
      this.$confirm(
        '您需先补充企业工资专户, 才能提交支付工资表',
        '工资专户未填写',
        {
          confirmButtonText: '前往完善',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          this.$router.push('/home/salary/salaryAccount')
          this.$store.commit('CHANGE_SLIDER_NAME', {
            oldUrl: '/home/salaryDf/companySalaryBatchList',
            newUrl: this.$router.currentRoute.fullPath,
          })
        })
        .catch(() => {})
    },
    noaccount(number) {
      var html =
        '<div>使用银联代发必须填写工资卡号，您的工资表中有' +
        "<span style='color:red'>" +
        number +
        '人</span>未填写工资卡号</div>'
      this.$confirm(html, '温馨提示', {
        dangerouslyUseHTMLString: true,
        type: 'warning',
        confirmButtonText: '返回编辑',
        cancelButtonText: '放弃提交',
      })
        .then((action) => {})
        .catch(() => {})
    },
    canpPapOff(data) {
      var html =
        "<div style='font-size:16px'>请核对工资表的数据是否正确</div>" +
        '<div>应发工资总额：' +
        "<span style='color:red'>￥" +
        data.shouldPay +
        '</span></div>' +
        '<div>应发工资人数：' +
        "<span style='color:red'>" +
        data.shouldPayTotal +
        '人</span>' +
        "&nbsp;&nbsp;<span style='color:#999'>(已排除" +
        data.deletedCount +
        '个应发工资等于0的人员)</span></div>'

      this.$confirm(html, '温馨提示', {
        dangerouslyUseHTMLString: true,
      })
        .then((action) => {
          this.isDisable = true
          this.toPaySalary(data)
        })
        .catch(() => {})
    },
    clearTimer() {
      var that = this
      if (this.timer) {
        clearTimeout(this.timer)
      }
    },
    isIE() {
      if (
        navigator.appName == 'Microsoft Internet Explorer' &&
        parseInt(
          navigator.appVersion
            .split(';')[1]
            .replace(/[ ]/g, '')
            .replace('MSIE', '')
        ) == 9
      ) {
        //是IE
        this.isIE9 = true
      } else {
        this.isIE9 = false
      }
    },
    getCompanyList() {
      this.axios({
        method: 'post',
        url: 'api-p/projectcompany/expand/findbyprojectid',
        data: {
          projectId: this.projectId,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.companyList = response.data.result
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    changeCompany() {
      this.$store.commit('SET_INFO', ['groupIdOptions', []])
      this.filterField.groupId = ''
      if (this.filterField.uscc) {
        this.getGroupList({
          projectId: this.projectId,
          uscc: this.filterField.uscc,
        })
      }
    },
    goBack() {
      this.$router.push({
        path: '/home/salaryDf/companySalaryBatchList',
        name: 'companySalaryBatchList',
        query: {
          projectId: this.projectId,
          // projectName:this.projectName,
        },
      })
      // this.$router.push("/home/constructSalary/importConstructSalary");
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/salaryDf/companySalaryBatchList',
        newUrl: this.$router.currentRoute.fullPath,
      })
      // }
    },
    //判断是否为未录入系统的员工
    checkEmployee(item) {
      if (item.remark && item.remark.indexOf('未录入系统人员') !== -1) {
        return true
      }
      return false
    },
    /**
     * @name: 驳回申请
     * @param {*}
     * @Author: 471826078@qq.com
     */
    refused() {
      this.showTask = true
    },
    handleCloseArea(val) {
      this.showTask = false
      if (val.success) {
        this.gotoDetail(val.reason)
      }
    },
    getStatusQuery(data) {
      this.statusQuery = data[0]
      this.rejectReason = data[1]
    },
    //驳回申请并跳转到工资表详情页
    gotoDetail(rejectReason) {
      this.$router.push({
        path: '/home/salaryDf/salaryPayBatchDetailList',
        name: 'salaryPayBatchDetailList',
        query: {
          salaryId: this.salaryId,
          yearQuery: this.year,
          monthQuery: this.month,
          statusQuery: 'REJECTED',
          month: this.month,
          batchNo: this.batchNo,
          sequenceCode: this.$route.query.sequenceCode,
          batchNoInfo: this.$route.query.batchNoInfo,
          rejectReason: this.rejectReason,
          projectId: this.projectId,
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/salaryDf/companySalaryBatchList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    callbackAddEmplyee(val) {
      this.formVisible = false
      if (val.success) {
        //需要刷新列表
        this.$nextTick(function () {
          this.getTableList(this.currentPage, this.pageSize)
        })
      }
    },
  },
}
</script>

<style scoped lang="less">
@import '../../../static/css/filterArea.less';
.mainCon {
  padding-top: 5px;
  padding-bottom: 24px;
  height: calc(100% - 67px);
  overflow-y: auto;
}
.mainConReject {
  top: 220px;
}
.el-table td div span {
  display: inline-block;
  width: 100%;
}

.el-main {
  color: red;
}
.redColor {
  color: red;
}
// 弹窗样式
.brand-dialog-min-width {
  .el-form-item /deep/ label {
    width: 130px !important;
  }
  .el-form-item /deep/ .el-form-item__content {
    margin-left: 130px !important;
  }
  .el-form-item /deep/ .el-textarea__inner {
    height: 130px;
  }
}

.btnContainer {
  text-align: center;
  padding-top: 40px;
  padding-bottom: 24px;
}

@media screen and (max-width: 1280px) {
  .input /deep/ .el-input__inner {
    width: 160px;
  }
  .searchInput /deep/ .el-input__inner {
    width: 190px;
  }
}

@media all and (min-width: 1360px) and (max-width: 1470px) {
  .input /deep/ .el-input__inner {
    width: 160px;
  }
  .searchInputWidth /deep/ .el-form--inline /deep/ .el-form-item__label {
    width: 68px;
  }
}

.saveBtn /deep/ .iconfont {
  padding: 0 5px;
  font-size: 14px;
}
.opetareText {
  margin-left: 0;
}
</style>
